import React, { FC, useRef, useImperativeHandle, forwardRef } from 'react'
import { Ajax } from '../api/api'


const UploadFile: FC<any> = forwardRef(({
    children,
    changePath
}, ref) => {
    const fileRef: any = useRef()
    const todoStartUpload = async () => {
        const file = fileRef.current.files[0]
        const data = new FormData()
        data.append('file', file)

        const res: any = await Ajax.uploadfile(data)
        if (res.code == 200) {
            changePath(res.path)
        }
    }

    useImperativeHandle(ref, () => {
        return {
            upload() {
                fileRef.current.click()
            }
        }
    })


    return (
        <div>
            <input type="file" style={{ display: 'none' }} ref={fileRef} onChange={todoStartUpload} />
            {
                children
            }
        </div>
    )
})

export default UploadFile